package com.blb.web;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.blb.utils.UUIDUtils;

@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 48161299820538556L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Collection<Part> parts = req.getParts();
		StringBuffer sb = new StringBuffer();
		int i =1;
		for (Part part : parts) {
			//获取http协议中content-disposition的信息
			String header = part.getHeader("content-disposition");
			//旧文件名，上传时的名称
			String name = header.substring(header.lastIndexOf("=")+2, header.length()-1);
			//新文件名，服务器重命名后的
			String newName = UUIDUtils.getID() + name.substring(name.lastIndexOf("."));
			
			sb.append(newName);
			if (i!=parts.size()) {
				sb.append(",");
			}
			//将文件将入D:/file_upload/
			part.write("D:/file_upload/" + newName);
			i++;
		}
		resp.getWriter().write("{\"name\" : \""+sb.toString()+"\"}");
	}
}
